package com.its.controller;

import com.its.domain.BaseResult;
import com.its.domain.CodeEnum;
import com.its.goods.pojo.Goods;
import com.its.goods.service.GoodsService;
import com.its.pojo.Cart;
import com.its.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @Autowired
    private GoodsService goodsService;

    //将商品加入购物车
    @PostMapping("/add")
    public BaseResult addToCart(@RequestParam Integer goodsId, @RequestParam Integer mount,HttpServletRequest request) {
        //查询要添加的商品
        Goods goods = goodsService.getById(goodsId);
        if (goods == null) {
            return BaseResult.error(CodeEnum.GOODS_NOT_FOUND);
        }
        //查询当前操作购物车的会员信息
        String memberAccount = (String) request.getAttribute("memberAccount");

        //将信息加入到购物车中
        cartService.addToCart(goods, mount,memberAccount);
        return BaseResult.ok();
    }


    //查询购物车
    @GetMapping("/list")
    public BaseResult<List<Cart>> getMyCart(HttpServletRequest request) {
        String memberAccount = (String) request.getAttribute("memberAccount");
        if (memberAccount == null) {
            return BaseResult.error(CodeEnum.UNAUTHORIZED); // 401
        }

        List<Cart> cartList = cartService.getCartByMemberAccount(memberAccount);
        return BaseResult.ok(cartList);
    }

    //将商品从我的购物车中删除
    @DeleteMapping("/remove")
    public BaseResult removeFromCart(@RequestParam Integer id,HttpServletRequest request) {
        String memberAccount = (String) request.getAttribute("memberAccount");
        if (memberAccount == null) {
            return BaseResult.error(CodeEnum.UNAUTHORIZED);
        }

        cartService.deleteToCart(id,memberAccount);
        return BaseResult.ok();
    }




}
